package com.rjyb.dyxz.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/DrawImg")
public class DrawImg extends HttpServlet {
    private static final Random r = new Random();
    private static final int width = 150;
    private static final int height = 40;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        Graphics img = image.getGraphics();
        img.setColor(Color.WHITE);
        img.fillRect(0,0,width,height);
        img.setColor(Color.WHITE);
        img.drawRect(1,1,width-2,height-2);
        img.setColor(Color.GREEN);
        for (int i = 0; i < 5; i++) {
            img.setColor(new Color(r.nextInt(155),r.nextInt(255),r.nextInt(255)));
            img.drawLine(0,r.nextInt(height),width,r.nextInt(height));
        }
        String srvCode = createRandomNum((Graphics2D) img);
        System.out.println(srvCode);
        req.getSession().setAttribute("srvCode",srvCode);
        resp.setContentType("image/jpeg");
        ImageIO.write(image,"jpg",resp.getOutputStream());
    }

    private String createRandomNum(Graphics2D img) {
        img.setColor(Color.RED);
        img.setFont(new Font("微软雅黑",Font.BOLD,20));
        String baseNum =  "0123456789QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjlzxcvbnm";
        return createRandomChar(img,baseNum);
    }

    private String createRandomChar(Graphics2D img, String baseNum) {
        StringBuffer sf = new StringBuffer();
        String ch = "";
        int j =5;
        for (int i = 0; i < 5; i++) {
            int degree = r.nextInt()%30;
            ch = baseNum.charAt(r.nextInt(baseNum.length()))+"";
            sf.append(ch);
            img.rotate(degree*Math.PI / 180,j,40);
            img.drawString(ch,j,30);
            img.rotate(-degree*Math.PI / 180,j,40);
            j+=30;
        }
        return sf.toString();
    }
}
